package com.ys.controller.api.eKnowAi;

import com.alibaba.fastjson.JSONObject;
import com.ys.entity.eKnowAi.EKnowKnowledgeBase;
import com.ys.entity.eKnowAi.EKnowKnowledgeList;
import com.ys.entity.eKnowAi.EKnowKnowledgeType;
import com.ys.enume.eKnowAi.EknowCodeEnum;
import com.ys.service.eKnowAi.EKnowKnowledgeListService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.file.ReadFileUtil;
import com.ys.vo.LayuiTableVoJA;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/knowledgeList")
public class ApiInterKnowledgeListController {
	private static final Logger logger = LoggerFactory.getLogger(ApiInterKnowledgeListController.class);

	@Autowired
	private ReadFileUtil readFileUtil;

	@Autowired
	private EKnowKnowledgeListService eKnowKnowledgeListService;

	@Autowired
	private CommonApiService<EKnowKnowledgeList> commonApiService;


	/**
	 * 设置查询的cond的sql设置
	 * @param cond
	 * @return
	 */
	public EKnowKnowledgeList setSeachSql(EKnowKnowledgeList cond){
		cond.addField("A.UpdateUserId + '/' + U.UserName AS userName");//操作人
		cond.addField("T.TypeName AS typeName");//分类名称
		cond.addLeftJoin("kjecp.dbo.TS_UserInfo U ON U.UserId = A.UpdateUserId");
		cond.addLeftJoin("kjecp_eknow.dbo.EKnow_KnowledgeType T ON T.Id = A.TypeId");
		//排序
		cond.setOrderby("A.SectionId DESC,A.UpdateTime ASC");
		return  cond;
	}


	/**
	 * 查询
	 */
	//@RequiresPermissions("eKnowKnowledgeList:view")
	@RequestMapping("/search")
	@ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
								 @ModelAttribute EKnowKnowledgeList cond
	){
		try {
			cond = setSeachSql(cond);
			LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
			return tableVoJA;
		}catch (Exception e){
			logger.error("查询出错：",e.getMessage(),e);
			LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
			tableVoJA.setCode(1);
			tableVoJA.setMsg("查询出错，请稍后重试！");
			return tableVoJA;
		}
	}


	/**
	 *	查询知识库资料信息
	 */
	@PostMapping("/searchKnowledgeListById")
	@ResponseBody
	public JSONObject searchKnowledgeListById(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			long id = Long.parseLong(params.get("id").toString());//知识库Id
			EKnowKnowledgeList eKnowKnowledgeList = new EKnowKnowledgeList().setId(id).queryFirst();
			List<EKnowKnowledgeType> eKnowKnowledgeTypeList = new EKnowKnowledgeType().setBaseId(eKnowKnowledgeList.getBaseId()).setOrderby("A.Sort ASC").queryList();
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			result.put("eKnowKnowledgeList", eKnowKnowledgeList);
			result.put("eKnowKnowledgeTypeList", eKnowKnowledgeTypeList);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("查询知识库资料信息出错：",e.getMessage(),e);
		}
		return result;
	}


	/**
	 *	查询知识库资料信息，根据分段id
	 */
	@PostMapping("/searchKnowledgeListBySectionId")
	@ResponseBody
	public JSONObject searchKnowledgeListBySectionId(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			String sectionId =params.get("sectionId").toString();//知识库分段id
			String baseId =params.get("baseId").toString();//知识库id
			List<EKnowKnowledgeList> eKnowKnowledgeList = new EKnowKnowledgeList().setSectionId(sectionId).queryList();
			List<EKnowKnowledgeType> eKnowKnowledgeTypeList = new EKnowKnowledgeType().setBaseId(Long.parseLong(baseId)).setOrderby("A.Sort ASC").queryList();
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			result.put("eKnowKnowledgeList", eKnowKnowledgeList);
			result.put("eKnowKnowledgeTypeList", eKnowKnowledgeTypeList);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("查询知识库资料信息出错：",e.getMessage(),e);
		}
		return result;
	}




	/**
	 * 新增、修改知识库资料信息
	 */
	@PostMapping("/addOrUpdateKnowledgeList")
	@ResponseBody
	public JSONObject addOrUpdateKnowledgeList(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			long baseId = Long.parseLong(params.get("baseId").toString());//知识库Id
			//long typeId = Long.parseLong(params.get("typeId").toString());//所属分类id
			//String information = params.get("information").toString();//内容

			int isSave = 0;
			EKnowKnowledgeBase eKnowKnowledgeBase = new EKnowKnowledgeBase().setId(baseId).queryFirst();
			if(eKnowKnowledgeBase!=null){
				String indexName = eKnowKnowledgeBase.getESIndexName();//索引名称
				if(params.get("addOrUpdate").toString().equals("add")) {//新增
					isSave = eKnowKnowledgeListService.addKnowledgeListByList(params,indexName);
				}else if(params.get("addOrUpdate").toString().equals("updateBySection")) {//按分段信息修改
					isSave = eKnowKnowledgeListService.updateKnowledgeListWithESBySection(params,indexName);
				}else {//修改
					isSave = eKnowKnowledgeListService.updateKnowledgeListWithES(params,indexName);
				}
				if(isSave>0){
					result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
				}else {
					result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
				}
			}else {
				result.put("code", EknowCodeEnum.ApiRetuenCode.NOBASE);
			}
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道新增、修改知识库资料信息出错：",e.getMessage(),e);
		}
		return result;
	}



	/**
	 * 导入知识库资料信息
	 */
	@PostMapping("/uploadLedgeFileList")
	@ResponseBody
	public JSONObject uploadLedgeFileList(MultipartFile file) {
		JSONObject result = new JSONObject();
		if (null != file) {
			try {
				String fileName = file.getOriginalFilename();
				String fileInfo = readFileUtil.readFileInfoByInputStream(file.getInputStream(),fileName);
				result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
				result.put("fileInfo", fileInfo);
				result.put("fileName", fileName);
			}catch (RuntimeException e) {

				result.put("code", EknowCodeEnum.ApiRetuenCode.PARAMSERROR);
			}catch (Exception e) {
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
				logger.error("逸知道新增、修改知识库资料信息出错：",e.getMessage(),e);
			}
		}else{
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
		}
		return result;
	}







	/**
	 * 删除知识库资料信息
	 */
	@PostMapping("/delKnowledgeList")
	@ResponseBody
	public JSONObject delKnowledgeList(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			long id = Long.parseLong(params.get("id").toString());//Id
			int isDel = eKnowKnowledgeListService.deleteKnowledgeListWithES(id);
			if(isDel>0){
				result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			}else {
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			}

		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道删除知识库资料信息出错：",e.getMessage(),e);
		}
		return result;


	}

	/**
	 * 批量删除知识库资料信息
	 */
	@PostMapping("/delKnowledgeListByBatch")
	@ResponseBody
	public JSONObject delKnowledgeListByBatch(HttpServletRequest request, HttpServletResponse response,@RequestParam("list")List<String> strList){
		JSONObject result = new JSONObject();
		try {
			int isDels = 0;
			for(String item:strList){
				long id = Long.parseLong(item);//Id
				int isDel = eKnowKnowledgeListService.deleteKnowledgeListWithES(id);
				if(isDel>0){
					isDels++;
				}
			}
			if(isDels>0){
				result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
			}else {
				result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			}

		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道批量删除知识库资料信息出错：",e.getMessage(),e);
		}
		return result;


	}




	/**
	 * 新增、修改知识库资料信息

	 @PostMapping("/addOrUpdateKnowledgeList")
	 @ResponseBody
	 public JSONObject addOrUpdateKnowledgeList(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
	 JSONObject result = new JSONObject();
	 try {
	 String loginUserId = ShiroUtils.getUserId();//登录的用户ID
	 long baseId = Long.parseLong(params.get("baseId").toString());//知识库Id
	 long typeId = Long.parseLong(params.get("typeId").toString());//所属分类id
	 String information = params.get("information").toString();//内容
	 List<String> informationList = new ArrayList<>();
	 informationList.add(information);

	 EKnowKnowledgeList eKnowKnowledgeList = new EKnowKnowledgeList();
	 eKnowKnowledgeList.setUpdateUserId(loginUserId);
	 eKnowKnowledgeList.setInformation(information);
	 eKnowKnowledgeList.setTypeId(typeId);

	 int isSave = 0;
	 EKnowKnowledgeBase eKnowKnowledgeBase = new EKnowKnowledgeBase().setId(baseId).queryFirst();
	 if(eKnowKnowledgeBase!=null){
	 String indexName = eKnowKnowledgeBase.getESIndexName();//索引名称
	 if(params.get("addOrUpdate").toString().equals("add")) {//新增
	 //接口入参
	 Map<String, Object> sendParams = new HashMap<>();
	 sendParams.put("information",informationList);
	 sendParams.put("indexName",indexName);
	 String sentUrl = URLAPI + "/api/outer/baiDuEKnowAi/addKnowledgeList";
	 //向量数据库新增向量数据接口
	 JSONObject addBack = apiHttpUtils.sendHttpPost(sendParams,sentUrl);
	 logger.info("返回参数："+addBack);
	 if(addBack.get("shardId")!=null){
	 List<String> shardIdList = (List<String>)addBack.get("shardId");
	 eKnowKnowledgeList.setESId(shardIdList.get(0));
	 eKnowKnowledgeList.setStatus(0);
	 eKnowKnowledgeList.setBaseId(baseId);
	 isSave = eKnowKnowledgeListService.addKnowledgeList(eKnowKnowledgeList);
	 }
	 }else {//修改
	 long id = Long.parseLong(params.get("id").toString());//Id
	 eKnowKnowledgeList.setStatus(1);
	 eKnowKnowledgeList.setId(id);
	 EKnowKnowledgeList eKnowKnowledgeListInfo = new EKnowKnowledgeList().setId(id).queryFirst();
	 if(eKnowKnowledgeListInfo!=null){
	 if(!eKnowKnowledgeListInfo.getInformation().equals(information)){//如果内容有修改
	 String eSId = eKnowKnowledgeListInfo.getESId();//向量数据库对应id
	 //接口入参
	 Map<String, Object> sendParams = new HashMap<>();
	 sendParams.put("information",informationList);
	 sendParams.put("indexName",indexName);
	 sendParams.put("shardId",eSId);
	 String sentUrl = URLAPI + "/api/outer/baiDuEKnowAi/updateKnowledgeList";
	 //向量数据库修改向量数据接口
	 JSONObject addBack = apiHttpUtils.sendHttpPost(sendParams,sentUrl);
	 logger.info("返回参数："+addBack);
	 if(addBack.get("shardId")!=null){
	 isSave = eKnowKnowledgeListService.updateKnowledgeList(eKnowKnowledgeList);
	 }
	 }else {//如果内容没有修改
	 isSave = eKnowKnowledgeListService.updateKnowledgeList(eKnowKnowledgeList);
	 }
	 }
	 }
	 if(isSave>0){
	 result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
	 }else {
	 result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
	 }
	 }else {
	 result.put("code", EknowCodeEnum.ApiRetuenCode.NOBASE);
	 }
	 }catch (Exception e) {
	 result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
	 logger.error("逸知道新增、修改知识库资料信息出错：",e.getMessage(),e);
	 }
	 return result;
	 }
	 */


}